package com.gexin.controller.system.order;

import com.alibaba.fastjson.JSONObject;
import com.alipay.AlipaySDK;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyApi;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.order.*;
import com.gexin.model.promo.PromoCode;
import com.gexin.model.promo.PromoInfo;
import com.gexin.model.promo.Promotional;
import com.gexin.model.shop.ShopInfo;
import com.gexin.model.system.AdminLog;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.uitls.WxConfig;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.PaymentApi;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单商品退款
 * @author 徐佳俊 2016-07-29
 *
 */

@ControllerBind(controllerKey = "/system/order/refundManage", viewPath = "WEB-INF/system/order")
public class OrderRefundController extends SystemBaseController {
	private static final Log log = Log.getLog(OrderRefundController.class);

	public void index() {

	}

	/**
	 * xu 2016-07-29 同意退款
	 */
	@Before(Tx.class)
	public void refund_ok() {
		String item_id = getPara("item_id");
		OrderItem orderItem = OrderItem.dao.getOrderItemById(item_id);
		OrderRefundApply orderRefundApply = OrderRefundApply.dao.getOrderRefundApplyByItemId(item_id);
		Order order = Order.dao.getOrderByOrderId(orderItem.getOrderId());
		if (order == null || !order.getShopId().equals(ShopInfo.shop_id)) {
			fail("非法访问!");
			return;
		}
		if (orderItem.getRefundState() == OrderRefundApply.State_Finsh) {
			fail("状态异常！");
			return;
		} else {
			String refund_id = IdGenerateUtils.getOrderId();
			String out_refund_id = null;// 外部退款的流水编号
			boolean execute_state = false;// 执行的状态
			Map<String, String> result_map = null;
			String refund_recv_accout = "微信公众号";

			//普通商品  订单总金额 也就是 退款金额
			BigDecimal total_fee=order.getTotalAmount();
			// 再判断是小程序还是APP
			if(order.getOrderPlatform()==1){ // 小程序支付
				//判断是普通订单还是预售商品 预售商品需要退款俩次
				if(order.getType()==1){ // 普通商品
					String ret = KusyApi.refund(KusyUtil.Api_key, KusyUtil.Sign_Key, order.getKusyOrderId(),order.getTotalAmount().doubleValue(), refund_id);
					JSONObject ret_obj =JSONObject.parseObject(ret);
					if(ret_obj.getInteger("status")==10000){
						out_refund_id=ret_obj.getString("refund_no");
						execute_state=true;
					}else{
						if(ret_obj.getInteger("status")==4001){
							fail("退款处理忠，请勿频繁申请");
							return;
						}else{
							fail(ret_obj.getString("message"));
							log.error("总后台同意退款 酷享支付失败，失败原因： "+ JsonKit.toJson(ret_obj));
							return;
						}
					}
				}else{  // 预售商品

					//退定金
					OrderPresale dingjin=OrderPresale.dao.findByOrderIdAndType(order.getId(),1);
					String ret_dj = KusyApi.refund(KusyUtil.Api_key, KusyUtil.Sign_Key, dingjin.getPayOrderid(),dingjin.getPayMoney().doubleValue(), refund_id+"_"+dingjin.getId());
					JSONObject ret_dj_obj =JSONObject.parseObject(ret_dj);
					if(ret_dj_obj.getInteger("status")==10000){
						out_refund_id=ret_dj_obj.getString("refund_no");
					}else{
						if(ret_dj_obj.getInteger("status")==4001){
							fail("退款处理忠，请勿频繁申请");
							return;
						}else{
							fail(ret_dj_obj.getString("message"));
							log.error("总后台同意退款 酷享支付失败，失败原因： "+ JsonKit.toJson(ret_dj_obj));
							return;
						}
					}

					//退尾款
					OrderPresale weikuan=OrderPresale.dao.findByOrderIdAndType(order.getId(),2);
					String ret_wk = KusyApi.refund(KusyUtil.Api_key, KusyUtil.Sign_Key, weikuan.getPayOrderid(), weikuan.getPayMoney().doubleValue() , refund_id+"_"+dingjin.getId());
					JSONObject ret_wk_obj =JSONObject.parseObject(ret_wk);
					if(ret_wk_obj.getInteger("status")==10000){
						out_refund_id=out_refund_id+","+ret_wk_obj.getString("refund_no");
						execute_state=true;
					}else{
						if(ret_wk_obj.getInteger("status")==4001){
							fail("退款处理忠，请勿频繁申请");
							return;
						}else{
							fail(ret_wk_obj.getString("message"));
							log.error("总后台同意退款 酷享支付失败，失败原因： "+ JsonKit.toJson(ret_wk_obj));
							return;
						}
					}


				}

			}else{ // APP支付
				if(order.getType()==1) { // 普通商品
					if(order.getPayType().intValue()==3){ //支付宝退款
						AlipayTradeRefundResponse resp=AlipaySDK.refund(order.getId(),order.getTotalAmount()+"");
						if(resp==null){
							fail("抱歉，支付宝退款失败！");
							return;
						}
						if(resp.isSuccess()){
							out_refund_id=IdGenerateUtils.getId();
							execute_state=true;
						}else{
							fail("请求失败，"+resp.getSubMsg());
							return;
						}
					}else{
						Map<String, String> para_map = new HashMap<String, String>();
						para_map.put("out_trade_no",order.getId());
						para_map.put("out_refund_no", refund_id);// 生成退款的订单ID
						para_map.put("total_fee",order.getTotalFee() + "");// 订单总金额
						para_map.put("refund_fee", order.getTotalFee() + "");// 退款金额
						para_map.put("appid", "wx001ef33c1c1512d9");
						para_map.put("mch_id", WxConfig.WXMchid);// 操作员的ID
//					para_map.put("op_user_id",wx_user.getOpenid());
						result_map = PaymentApi.refund(para_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
						if (result_map == null||result_map.get("return_code").equals("FAIL")) {
							fail("请求错误，请稍后再试！");
							log.error("总后台同意退款 PaymentApi 支付失败，失败原因："+JsonKit.toJson(result_map)+"，支付参数："+para_map);
							return;
						}else
							execute_state =result_map.get("result_code").equals("SUCCESS");
						if (!execute_state) {
							fail(result_map.get("err_code_des"));
							return;
						}
						out_refund_id = result_map.get("refund_id");
					}
				}else{ //预售商品 退2次
					if(order.getPayType().intValue()==3) { //支付宝退款
						//退定金
						OrderPresale dingjin=OrderPresale.dao.findByOrderIdAndType(order.getId(),1);
						AlipayTradeRefundResponse resp=AlipaySDK.refund(order.getId()+"_"+dingjin.getId(),dingjin.getPayMoney()+"");
						if(resp.isSuccess()){
							out_refund_id=IdGenerateUtils.getId();
						}else{
							System.err.println(JsonKit.toJson(resp));
							fail("请求失败，"+resp.getSubMsg());
							return;
						}
						//退尾款
						OrderPresale weikuan=OrderPresale.dao.findByOrderIdAndType(order.getId(),2);
						AlipayTradeRefundResponse resp2=AlipaySDK.refund(order.getId()+"_"+weikuan.getId(),weikuan.getPayMoney()+"");
						if(resp2.isSuccess()){
							out_refund_id=out_refund_id+","+IdGenerateUtils.getId();
						}else{
							fail("请求失败，"+resp2.getSubMsg());
							return;
						}

						execute_state=true;
					}else{
						//退定金
						OrderPresale dingjin=OrderPresale.dao.findByOrderIdAndType(order.getId(),1);
						Map<String, String> dj_map = new HashMap<String, String>();
						dj_map.put("out_trade_no",order.getId()+"_"+dingjin.getId());
						dj_map.put("out_refund_no", refund_id);// 生成退款的订单ID
						dj_map.put("total_fee",dingjin.getPayMoney().multiply(BigDecimal.valueOf(100)).setScale(0) + "");// 订单总金额
						dj_map.put("refund_fee", dingjin.getPayMoney().multiply(BigDecimal.valueOf(100)).setScale(0) + "");// 退款金额
						dj_map.put("appid", "wx001ef33c1c1512d9");
						dj_map.put("mch_id", WxConfig.WXMchid);
//					dj_map.put("op_user_id", WxConfig.WXMchid);// 操作员的ID
						result_map = PaymentApi.refund(dj_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
						if (result_map == null||result_map.get("return_code").equals("FAIL")) {
							fail("请求错误，请稍后再试！");
							log.error("总后台同意退款 PaymentApi 支付失败，失败原因："+JsonKit.toJson(result_map));
							return;
						}
						out_refund_id = result_map.get("refund_id");
						//退尾款
						OrderPresale weikuan=OrderPresale.dao.findByOrderIdAndType(order.getId(),2);
						Map<String, String> wk_map = new HashMap<String, String>();
						wk_map.put("out_trade_no",order.getId()+"_"+weikuan.getId());
						wk_map.put("out_refund_no", refund_id);// 生成退款的订单ID
						wk_map.put("total_fee",weikuan.getPayMoney().multiply(BigDecimal.valueOf(100)).setScale(0) + "");// 订单总金额
						wk_map.put("refund_fee", weikuan.getPayMoney().multiply(BigDecimal.valueOf(100)).setScale(0) + "");// 退款金额
						wk_map.put("appid", "wx001ef33c1c1512d9");
						wk_map.put("mch_id", WxConfig.WXMchid);
//					wk_map.put("op_user_id", WxConfig.WXMchid);// 操作员的ID
						result_map = PaymentApi.refund(wk_map, WxConfig.WXKEY, WxConfig.KEYSTORE_FILE);
						if (result_map == null||result_map.get("return_code").equals("FAIL")) {
							fail("请求错误，请稍后再试！");
							log.error("总后台同意退款 PaymentApi 支付失败，失败原因："+JsonKit.toJson(result_map));
							return;
						}else
							execute_state =result_map.get("result_code").equals("SUCCESS");
						if (!execute_state) {
							fail(result_map.get("err_code_des"));
							return;
						}
						out_refund_id =out_refund_id+","+result_map.get("refund_id");
					}


				}
			}
			if (execute_state) {
				// 保存账单信息
				OrderRefund refund = new OrderRefund();
				refund.setRefundId(refund_id);
				refund.setOrderId(order.getId());
				refund.setRefundFee(order.getTotalAmount().intValue()*100);
				refund.setItemId(orderItem.getItemId());
				refund.setRefundRecvAccout(refund_recv_accout);
				refund.setState(1);
				refund.setIsAddFreight(orderRefundApply.getIsAddFreight());
				refund.setOutRefundNo(out_refund_id);
				refund.save();
				// 判断订单总数
				Long item_count = Db.queryLong("select count(1) from t_order_item   where order_id=?", order.getId());
				order.setRefundAmount(order.getRefundAmount().add(orderRefundApply.getRefundAmount()));// 设置订单的退款金额
				if (item_count == 1) {
					// 只有一个订单直接把订单完成了 要重新计算费用
					int state = order.getTotalAmount().compareTo(orderRefundApply.getRefundAmount());
					if (state == 0) {
						// 如果等于
						order.setJsAmount(order.getTotalAmount().subtract(orderRefundApply.getRefundAmount()));
					} else if (state == 1) {
						// 如果还有剩下的钱 开始给商家加进去
						order.setJsAmount(order.getTotalAmount().subtract(orderRefundApply.getRefundAmount()));
						order.setJsFlag(3);
						// 如果订单的金额大于退款的金额
					} else {
						// 小于 订单异常信息
						AdminLog.dao.addLog(AdminLog.Log_Type.LOG_ERROR,1, String.format("订单ID：%s,ItemId:%s,退款金额大于商品金额", orderItem.getOrderId(), orderItem.getItemId()));
						fail("退款金额大于商品金额，请联系管理员！");
						return;
					}
					//把优惠券状态改回去

					//判断下是否有用优惠券
					if(!StringUtils.isEmpty(order.getCouponId())){
						UserCoupon userCoupon=UserCoupon.dao.findByUserIdAndCoupon(order.getUserId(),order.getCouponId());
						if(userCoupon!=null){
							if(userCoupon.getUseState()==99){
								userCoupon.setUseState(0);
								userCoupon.update();
							}
						}
					}
					order.setState(OrderState.State_Closed);// 把订单直接完成了
					order.setModifiedTime(new Date());
					order.update();
				} else {
					// =========================================== 只有出现购物车的时候才会出现这个问题
					List<OrderItem> orderItem_list = OrderItem.dao.getItembyId(orderItem.getOrderId());
					
					BigDecimal preferentialAmount=BigDecimal.ZERO;//优惠金额
					
					//优惠券兑换码优惠金额
					if (order.getCouponId()!=null) {
						UserCoupon coupon= UserCoupon.dao.findById(order.getCouponId());
						if (coupon!=null) {
							Promotional promotional= Promotional.dao.findById(coupon.getPromotionalId());
							if (promotional!=null) {
								if (promotional.getPlatformType()==2) {
									if (promotional.getUseId().equals(String.valueOf(orderItem.getProductId()))) {
										preferentialAmount=order.getCouponAmount();
									}
								}else {
									int num = 0;
									for (int i = 0; i < orderItem_list.size(); i++) {
										if (orderItem_list.get(i).getRefundState() != 1) {
											num++;
										}
									}
									if (num == orderItem_list.size()-1) {
										preferentialAmount=order.getCouponAmount();
									}
								}
							}
						}
					}
					if (order.getPromoCode()!=null) {
						PromoCode promoCode= PromoCode.dao.findById(order.getPromoCode());
						if (promoCode!=null) {
							PromoInfo promoInfo= PromoInfo.dao.findById(promoCode.getPromoInfoId());
							if (promoInfo!=null) {
								if (promoInfo.getProductId().equals(orderItem.getProductId())) {
									preferentialAmount=order.getPromoMoney();
								}
							}
						}
					}

					int o = 0;
					for (int i = 0; i < orderItem_list.size(); i++) {
						if (orderItem_list.get(i).getRefundState() == 5) {
							o++;
						}
					}
					if (o == orderItem_list.size()-1) {  //所有商品退款完成
						order.setState(OrderState.State_Closed);
					}
					order.setModifiedTime(new Date());
					order.update();
					// 多个订单处理这里就麻烦了
					log.info(String.format("退款完成，订单ID：%s,退款金额:%s", order.getId(), order.getRefundAmount()));
				}
				
				orderItem.setRefundState(OrderRefundApply.State_Finsh);
				orderRefundApply.setRefundState(OrderRefundApply.State_Finsh);
				//===========================================================
				if (orderItem.update() && orderRefundApply.update()) {
					success("操作成功");
				} else {
					fail("请稍后再试11");
				}
			} else {
				fail("发生未知错误！");
			}

		}
	}

	/** 拒绝退款 */
	public void refund_no() {
		String item_id = getPara("item_id");
		String reason = getPara("reason");
		OrderItem orderItem = OrderItem.dao.getOrderItemById(item_id);
		OrderRefundApply orderRefundApply = OrderRefundApply.dao.getOrderRefundApplyByItemId(item_id);
		Order order = Order.dao.getOrderByOrderId(orderItem.getOrderId());
		if (order == null || !order.getShopId().equals(ShopInfo.shop_id)) {
			fail("非法访问!11");
			return;
		}
		if (getParaToInt("refund_state") != orderItem.getRefundState()) {
			fail("状态异常！");
		} else {

			orderItem.setRefundState(4);
			orderRefundApply.setRefuseReason(reason);// 退款理由
			orderRefundApply.setRefundState(3);
			// orderRefundApply.setReject_reason(getPara("reject_reason"));//拒绝原因
			if (orderItem.update() && orderRefundApply.update()) {
				if (StringUtil.isBlank(order.getExpressName())) {
					order.setState(OrderState.State_Pay_OK);
				} else {
					order.setState(OrderState.State_Express_OK);
				}
				order.setModifiedTime(new Date());
				order.update();
				success("操作成功");
			} else {
				fail("请稍后再试");
			}
		}
	}

	// 同意退货申请，发送退货地址
	public void refund_adrr_ok() {
		String item_id = getPara("item_id");
		String adrr = getPara("address");
		OrderItem orderItem = OrderItem.dao.getOrderItemById(item_id);
		OrderRefundApply orderRefundApply = OrderRefundApply.dao.findById(getPara("id"));
		Order order = Order.dao.getOrderByOrderId(orderItem.getOrderId());
		if (order == null || !order.getShopId().equals(ShopInfo.shop_id)) {
			fail("非法访问!");
			return;
		}
		if (orderItem.getRefundState() == OrderRefundApply.State_Finsh) {
			fail("状态异常！");
			return;
		}
		orderRefundApply.setRefundAdminName(getPara("refund_admin_name"));
		orderRefundApply.setRefundAdminRemark(getPara("refund_admin_remark"));
		orderRefundApply.setRefundAdminPhone(getPara("refund_admin_phone"));
		orderRefundApply.setRefundAdrr(adrr);
		orderRefundApply.setRefundState(OrderRefundApply.State_adrr_apply);
		if (orderRefundApply.update()) {
			success("操作成功");
		} else {
			fail("操作失败");
		}
	}


	/**
	 * 黎峻封的成功方法
	 */
	public void refundSuccess(){

	}

}
